package edu.whu.rose.clock.ssql.util;

public class IntLinkedList {

	private IntLinkedNode head;
	private IntLinkedNode end;
	
	public IntLinkedList() {
		this(null);
	}
	
	public IntLinkedList(IntLinkedNode head) {
		this.head = head;
		this.end = head;
	}
	
	public void insertAtEnd(IntLinkedNode node) {
		if (end == null) {
			this.head = node;
			this.end = node;
		}
		else {
			end.setNext(node);
			this.end = node;
		}
	}
	
	public void switchToEnd(int index) {
		IntLinkedNode iln = this.head;
		if (iln.getIndex() == index) {
			if (iln.getNext() != null) {
				this.head = iln.getNext();
				this.end.setNext(iln);
				this.end = iln;
			}
			return;
		}
		for (; iln.getNext() != null && iln.getNext().getIndex() != index; iln = iln.getNext());
		if (iln.getNext() == null) {
			System.out.println("Error: found index " + index + " in cache but not in queue");
		}
		IntLinkedNode temp = iln.getNext();
		if (temp != this.end) {
			iln.setNext(temp.getNext());
			this.end.setNext(temp);
			this.end = temp;
		}
	}
	
	public IntLinkedNode removeHead() {
		IntLinkedNode iln = this.head;
		if (this.head == this.end) {
			this.head = null;
			this.end = null;
		}
		else {
			head = head.getNext();
		}
		
		return iln;
	}
	
	public void delete(int index) {
		IntLinkedNode iln = this.head;
		if (iln.getIndex() == index) {
			if (this.end == this.head) {
				this.head = null;
				this.end = null;
			}
			else {
				this.head = iln.getNext();
			}
			return;
		}
		for (; iln.getNext() != null && iln.getNext().getIndex() != index; iln = iln.getNext());
		if (iln.getNext() == null) {
			System.out.println("Error: found index " + index + " in cache but not in queue");
		}
		iln.setNext(iln.getNext().getNext());
	}
	
	public void deleteAtEnd(int index) {
		if (this.end != null && this.end.getIndex() == index) {
			IntLinkedNode iln = this.head;
			if (iln == this.end) {
				this.head = null;
				this.end = null;
				return;
			}
			for (; iln.getNext() != this.end; iln = iln.getNext());
			iln.setNext(null);
			this.end = iln;
		}
		else {
			System.out.println("Error: cannot find the correct end of the queue");
		}
	}
	
}
